<template>
    <view class="shopCart pb-200">
        <Navigation title="购物车" background="#fff" />
        <!-- <view class="pt-19 tab">
            <u-tabs
                :list="typeList"
                @click="click"
                lineColor="#FABB3C"
                :activeStyle="{ color: '#222222', fontSize: '28rpx', fontWeight: '600' }"
                :inactiveStyle="{ color: '#999999', fontSize: '28rpx', fontWeight: '400' }"
                lineWidth="28rpx"
                lineHeight="6rpx"
                :itemStyle="{ width: '50%', height: '80rpx' }"
            ></u-tabs>
        </view> -->
        <view class="pv-32 ph-40 address" @click="toAddress">
            <view class="f ai-c jc-s-b">
                <view class="fs-28 text-color4">收货地址</view>
                <image src="http://cwht.ricecs.cn/app/shop/edit.png" class="w-32 h-32" @click.stop="handleEdit" v-show="!isEdit"></image>
                <view @click.stop="handleOver" v-show="isEdit" class="fs-28 fw-500 text-color">退出编辑</view>
            </view>
            <view class="mt-25" v-if="addressData">
                <view class="f ai-c">
                    <view class="w-104 h-32 b-4 default f ai-c jc-c fs-22 text-color5 mr-16" v-show="addressData.defaultStatus">默认地址</view>
                    <view class="fs-28 fw-500 text-color4">{{ addressData.name }} {{ phoneNumbe(addressData.mobile) }}</view>
                </view>
                <view class="fs-24 text-color3 mt-16">地址：{{ addressData.areaName }}{{ addressData.detailAddress }}</view>
            </view>
            <view v-else class="mt-32 fs-28 fw-500 text-color3">请选择地址~</view>
        </view>
        <view class="list b-24 pt-32 ph-32 mt-20" v-for="(item, index) in list" :key="index">
            <view class="ml-8 fs-28 fw-600 text-color4">{{ item.shop }}</view>
            <view class="mt-32 pb-32 f ai-c" v-for="(items, indexs) in item.goods" :key="indexs">
                <image :src="items.selected ? selectCheck : select" class="w-32 h-32 mr-32" @click="handleSelect(items, index, indexs)"></image>
                <view class="f f1 ai-c" v-if="items.sku">
                    <image :src="items.sku.picUrl" class="w-160 h-160 b-12 mr-32"></image>
                    <view class="f fd-c f1">
                        <view class="fs-32 fw-600 text-color4 text-ellipsis-2">{{ items.spu.name }}</view>
                        <view class="mt-12">
                            <text class="fs-22 text-color8">¥</text>
                            <text class="fs-36 fw-600 text-color8">{{ items.sku.price }}</text>
                        </view>
                        <view class="f ai-c jc-s-b">
                            <view class="fs-24 text-color6"> </view>
                            <u-number-box
                                v-model="items.count"
                                :min="1"
                                :max="items.sku.stock"
                                :disablePlus="items.count == items.sku.stock"
                                :disableMinus="items.count == 1"
                                integer
                                :disabledInput="items.count >= items.sku.stock"
                                @change="changeNum(items)"
                            ></u-number-box>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="f ai-c jc-s-b bot h-180 w-f pl-32 pr-40" :style="{ paddingBottom: safeAreaBottom + 'px' }">
            <view class="f ai-c">
                <view class="f ai-c" @click="allSelect">
                    <image :src="allCheck ? selectCheck : select" class="w-32 h-32 mr-16"></image>
                    <view class="fs-24 text-color4">全选</view>
                </view>
                <view class="ml-24" v-show="!isEdit">
                    <text class="fs-32 text-color4">合计:</text>
                    <text class="fs-22 text-color8">¥</text>
                    <text class="fs-36 fw-600 text-color8">{{ totalPrice }}</text>
                </view>
            </view>

            <view class="w-200 h-80 b-80 fs-28 fw-500 text-color5 btn f ai-c jc-c" @click="toConfirmOrder" v-show="!isEdit">去结算</view>
            <view class="w-200 h-80 b-80 fs-28 fw-500 text-color5 btn f ai-c jc-c" @click="delCart" v-show="isEdit">删除</view>
        </view>
    </view>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { addressGetDefault } from '@/services/api/address';
import { cartUpdateSelected, cartUpdateCount, cartDelete, cartList } from '@/services/api/shop/cart';
import { onShow } from '@dcloudio/uni-app';
import { phoneNumbe } from '@/utils/global';
import selectCheck from '@/static/select-check.png';
import select from '@/static/select.png';
const authStore = useAuthStore();
const addressData = ref<any>({});
const list = ref<any[]>([]);
const isEdit = ref(false);
//总价
const totalPrice = computed(() => {
    let price = 0;
    list.value.forEach((item) => {
        item.goods.forEach((items: any) => {
            if (items.selected&&items.sku) {
                price += Number(items.sku.price) * Number(items.count); //未加运费
            }
        });
    });
    return price.toFixed(2);
});
onShow(() => {
    let pages = getCurrentPages();
    let currPage: any = pages[pages.length - 1];
    let addressDatas = currPage.data.addressData;

    //选择地址
    if (addressDatas) {
        addressData.value = addressDatas;
    } else {
        getDefaultAddress();
        getCartList();
    }
});
const toConfirmOrder = () => {
    const data: any[] = [];

    list.value.forEach((item) => {
        const lists: any[] = [];
        item.goods.forEach((items) => {
            if (items.selected) {
                lists.push(items);
            }
        });
        if (lists.length > 0) {
            data.push({
                shop: item.shop,
                goods: lists,
            });
        }
    });
    console.log(data, 111);
    if (data.length == 0) {
        uni.showToast({
            title: '请选择商品',
            icon: 'none',
        });
        return;
    }
    authStore.setOrderGoods(data);
    uni.navigateTo({
        url: '/pages_shop/confirmOrder/index',
    });
};
//完成编辑
function handleOver() {
    isEdit.value = !isEdit.value;
    getCartList();
}
//编辑
function handleEdit() {
    isEdit.value = !isEdit.value;
    allCheck.value = false;
    list.value.forEach((item) => {
        item.goods.forEach((items: any) => {
            if (items.selected) {
                items.selected = false;
            }
        });
    });
}
//删除
async function delCart() {
    uni.showModal({
        title: '提示',
        content: '确认删除？',
        success: async function (res) {
            if (res.confirm) {
                let ids: any[] = [];
                list.value.forEach((item) => {
                    item.goods.forEach((items: any) => {
                        if (items.selected) {
                            ids.push(items.id);
                        }
                    });
                });
                await cartDelete(ids);
                const { data } = await cartList({});
                list.value = [];
                for (let k in data.validList) {
                    list.value.push({
                        shop: k,
                        goods: data.validList[k],
                    });
                }
                allCheck.value = false;
                list.value.forEach((item) => {
                    item.goods.forEach((items: any) => {
                        if (items.selected) {
                            items.selected = false;
                        }
                    });
                });
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        },
    });
}

//全选
const allCheck = ref(false);

//跳转地址
function toAddress() {
    uni.navigateTo({
        url: `/pages_mine/myAddress?type=select`,
    });
}
//改变数量
async function changeNum(data: any) {
    await cartUpdateCount({ id: data.id, count: data.count });
}
//选择框
async function handleSelect(data: any, index: number, indexs: number) {
    list.value[index].goods[indexs].selected = !list.value[index].goods[indexs].selected;
    await cartUpdateSelected({ ids: [data.id], selected: list.value[index].goods[indexs].selected });
    const selected: boolean[] = [];
    list.value.forEach((item) => {
        item.goods.forEach((items: any) => {
            selected.push(items.selected);
        });
    });
    allCheck.value = selected.every((item) => item);
}
//全选
async function allSelect() {
    allCheck.value = !allCheck.value;
    let ids: any[] = [];
    list.value.forEach((item) => {
        item.goods.forEach((items: any) => {
            ids.push(items.id);
            items.selected = allCheck.value;
        });
    });
    await cartUpdateSelected({ ids, selected: allCheck.value });
}

//获取购物车列表
async function getCartList() {
    const { data } = await cartList({});
    list.value = [];
    for (let k in data.validList) {
        list.value.push({
            shop: k,
            goods: data.validList[k],
        });
    }
    const selected: boolean[] = [];
    list.value.forEach((item) => {
        item.goods.forEach((items: any) => {
            selected.push(items.selected);
        });
    });
    allCheck.value = selected.every((item) => item);
}
//获取默认地址
async function getDefaultAddress() {
    const { data } = await addressGetDefault({});
    addressData.value = data;
}
//底部安全距离
const systemInfo = uni.getSystemInfoSync();
let safeArea = systemInfo.safeArea;
let screenHeight = systemInfo.screenHeight;
let safeAreaBottom = screenHeight - safeArea.bottom;
</script>
<style lang="scss" scoped>
.shopCart {
    background: #f2f2f2;
    min-height: 100vh;
    .bot {
        position: fixed;
        left: 0;
        bottom: 0;
        background: #fff;
        z-index: 111;
        .btn {
            background: #fabb3c;
        }
    }
    ::v-deep.u-number-box__plus {
        background: #fff !important;
        width: 40rpx !important;
    }
    ::v-deep .u-number-box__minus {
        background: #fff !important;
        width: 40rpx !important;
    }
    ::v-deep .u-icon__icon {
        font-size: 20rpx !important;
    }
    ::v-deep .u-number-box__input {
        width: 80rpx !important;
        height: 40rpx !important;
        background: #f4f4f4 !important;
        border-radius: 4rpx !important;
        font-family: PingFangSC-Medium;
        font-weight: 500 !important;
        font-size: 24rpx !important;
        color: #1a1a1a !important;
    }
    .list {
        background: #fff;
    }
    .default {
        background: #f54040;
    }
    .tab {
        background: #fff;
    }
    .address {
        background: #fff;
        border-radius: 0 0 24rpx 24rpx;
    }
}
</style>
